package com.kaibes.module.token.listener;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.kaibes.module.token.pojo.Token;
import com.kaibes.module.token.pojo.TokenLog;
import com.kaibes.module.token.pojo.TokenLogType;
import com.kaibes.module.token.service.TokenLogService;
import com.kaibes.module.token.service.TokenService;
import com.kaibes.module.user.UserService;
import com.kaibes.orm.core.listener.DeleteListener;
import com.kaibes.orm.curd.Delete;
import com.kaibes.orm.spring.OrmListener;

@OrmListener(service = TokenService.class)
public class TokenDeleteListener implements DeleteListener {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private TokenLogService tokenLogService;
    
    private ThreadLocal<List<Token>> store = new ThreadLocal<>();
    
    @Override
    public void beforeDelete(Delete delete) throws Exception {
        List<Token> tokenList = tokenService.list(delete.getQueries(), "user_id");
        if (!tokenList.isEmpty()) {
            store.set(tokenList);
        }
    }
    
    @Override
    public void afterDelete(Delete delete, int count) throws Exception {
        List<Token> tokenList = store.get();
        if (tokenList != null) {
            store.remove();
            List<TokenLog> logList = new ArrayList<>();
            for (Token e : tokenList) {
                TokenLog tokenLog = new TokenLog();
                tokenLog.setUserId(e.getUserId());
                tokenLog.setType(TokenLogType.DELETE);
                tokenLog.setCreateTime(LocalDateTime.now());
                logList.add(tokenLog);
                if (userService != null) {
                    userService.updateLogoutTimeById(e.getUserId(), tokenLog.getCreateTime());
                }
            }
            tokenLogService.save(logList);
        }
    }
    
}
